package com.zhuyuan.security.filter;

import com.zhuyuan.core.constant.InnerContsants;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * @Author: 张琳凯
 * @Description: 拦截请求，如果请求头中包含X-Internal-Request，则添加一个匿名认证，允许访问受保护的资源
 * 内部信任机制: 因为feign需要携带token，所以需要内部信任机制
 * @DateTime: 2025/2/26 22:15
 **/
public class FeignInternalTrustFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String trustHeader = request.getHeader(InnerContsants.INNER_INTERNAL_HEADER);
        if (InnerContsants.INNER_INTERNAL_VALUE.equals(trustHeader)) {
            // 添加一个匿名认证，允许访问受保护的资源
            request.setAttribute(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY, InnerContsants.INNER_INTERNAL_USER);
            SecurityContextHolder.getContext().setAuthentication(
                    new UsernamePasswordAuthenticationToken(InnerContsants.INNER_INTERNAL_USER, null, new ArrayList<>())
            );
        }
        filterChain.doFilter(request, response);
    }
}
